package com.business.form.action;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; 

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.business.base.BaseController;
import com.business.base.Pager;
import com.business.form.po.FormBean;
import com.business.form.po.FormColumnBean;
import com.business.form.service.FormColumnService;
import com.business.form.service.FormControlService;
import com.business.form.service.FormParamsService;
import com.business.form.service.FormParamsValueService;
import com.business.form.service.FormReadService;
import com.business.form.service.FormSaveService;
import com.business.form.service.FormService;
import com.common.ErrorLog;
import com.common.NumberProcess;
import com.common.RenderPage;
import com.common.StringProcess;
import com.common.utils.SpringContextHolder;


/**
 * @author jpx 
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping(value="/form/formColumn")
public class FormColumnController{
	
	@Autowired
	FormColumnService formColumnService;
	
	@Autowired
	FormService formService;
	
	@Autowired
	FormParamsService formParamsService;
	
	@Autowired
	FormReadService formReadService;

	@RequestMapping(value="/nav")
	public String nav(HttpServletRequest request,ModelMap model) {
				
		StringBuilder leftUrlParams=new StringBuilder();
		leftUrlParams.append("dataMapper=form.form.selectTree");
		leftUrlParams.append("&");
		leftUrlParams.append("searchMapper="+URLEncoder.encode("{\"pageClassifyCode\":\"lby\"}"));
		leftUrlParams.append("&");
		leftUrlParams.append("clickScript="+URLEncoder.encode("parent.document.getElementById('right').src='../../form/formColumn/list?nodeId=url.NodeId&parentNodeId=url.ParentNodeId';"));
		model.put("leftUrlParams", leftUrlParams.toString());
		
		model.put("rightUrl", "../../form/formColumn/list");
		
		return "/components/navpage/nav";
	}
	
	@RequestMapping(value="/list")
	public String list(HttpServletRequest request,ModelMap model) {
		String nodeId=StringProcess.getRequest(request.getParameter("nodeId"), "");
		String parentNodeId=StringProcess.getRequest(request.getParameter("parentNodeId"), "");
		
		model.put("nodeId", nodeId);
		model.put("parentNodeId", parentNodeId);
		
		return "/form/formColumn/list";
	}

	@RequestMapping({ "/detail" })
	public String detail(HttpServletRequest request, ModelMap model) {
		try{

		    String formColumnId = StringProcess.getRequest(request.getParameter("formColumnId"), "");
		    String nodeId=StringProcess.getRequest(request.getParameter("nodeId"), "");

			//初始化控件
			String formId=nodeId;
						
			String action = "";
			FormColumnBean bean=new FormColumnBean();
			if (formColumnId.length() == 0) {
				action = "insert";
			    formColumnId = StringProcess.getUUID();
				bean.setFormColumnId(formColumnId);
				
				bean.setFormId(formId);

			} else {
				action = "update";
				bean=formColumnService.getBeanByKeyId(formColumnId);
				
				formId=bean.getFormId();
			}
			
			
			//参数列
			Map<String, Object> paramMap = new HashMap<String, Object>();
			int objectType=31;
			paramMap.put("objectType",objectType);
			paramMap.put("objectId",formColumnId);
			List<Map<String, Object>> listFormParams = formParamsService.select(paramMap);
			BaseController.ProcessParams(model, listFormParams);
						
			
			
			String formName="";
			if(bean.getFormId().length()>0 )
			{
				paramMap=new HashMap<String, Object>();
				paramMap.put("pageClassifyCode", "lby");
				paramMap.put("formId", bean.getFormId());
				
				List<Map<String,Object>> list=formService.selectTree(paramMap);
				for(int i=0;i<list.size();i++)
				{
					Map<String,Object> item=list.get(i);
					formName=item.get("NodeText").toString();
				}
			}
			
			//读取formRead-form
			if(formId.length()>0)
			{
				paramMap = new HashMap<String, Object>();
				paramMap.put("formId",formId);
				paramMap.put("readType",1);
				List<Map<String, Object>> listFormRead = formReadService.select(paramMap);
				String parentTableId="";
				for(int i=0;i<listFormRead.size();i++)
				{
					if(i>0)
					{
						parentTableId+=",";
					}
					parentTableId+=listFormRead.get(i).get("ReadTableId");
				}
				model.put("parentTableId", parentTableId);
			}
			
			
			//读取formRead-Control
			if(formColumnId.length()>0)
			{
				paramMap = new HashMap<String, Object>();
				paramMap.put("formId",formId);
				paramMap.put("formColumnId",formColumnId);
				paramMap.put("readType",2);
				List<Map<String, Object>> listFormRead = formReadService.select(paramMap);
				String readTableId="";
				String readTableName="";
				String readFieldId="";
				String readFieldName="";
				for(int i=0;i<listFormRead.size();i++)
				{
					if(i>0)
					{
						readTableId+=",";
						readTableName+=",";
						readFieldId+=",";
						readFieldName+=",";
					}
					readFieldId+=listFormRead.get(i).get("ReadFieldId");
					readFieldName+=(listFormRead.get(i).get("ReadTableName")+"."+listFormRead.get(i).get("ReadFieldName"));
					readTableId+=listFormRead.get(i).get("ReadTableId");
					readTableName+=listFormRead.get(i).get("ReadTableName");
				}
				model.put("readFieldId", readFieldId);
				model.put("readFieldName", readFieldName);
				model.put("readTableId", readTableId);
				model.put("readTableName", readTableName);
			}
			

			model.put("action", action);
			model.put("bean", bean);
			model.put("formName", formName);
			
		}catch(Exception e){
			ErrorLog.OnWrite(e);
		}
		
		return "/form/formColumn/detail";
	}
	
	@RequestMapping("/getTableByFormId")
	public void getTableByFormId(HttpServletResponse response,String formId) {
		String ret="";
		
		if(formId.length()>0)
		{
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap = new HashMap<String, Object>();
			paramMap.put("formId",formId);
			paramMap.put("readType",1);
			List<Map<String, Object>> listFormRead = formReadService.select(paramMap);
			String readTableId="";
			for(int i=0;i<listFormRead.size();i++)
			{
				if(i>0)
				{
					readTableId+=",";
				}
				readTableId+=listFormRead.get(i).get("ReadTableId");
			}
			ret=readTableId;
		}
		
		RenderPage.JsonByString(response, ret);
	}
	
	@RequestMapping("/query")
	public void query(Integer pageIndex, Integer pageSize, HttpServletRequest request, HttpServletResponse response,
			ModelMap map) {
			
		try{
			Map<String, Object> search = new HashMap<String, Object>();
			
			//筛选条件
			String nodeId=StringProcess.getRequest(request.getParameter("nodeId"), "");
			if(nodeId.length()>0)
			{
				if(StringUtils.isNotEmpty(nodeId)){
					search.put("formId", nodeId);
				}
				
				Pager<Map<String, Object>> result = formColumnService.selectPage(pageIndex,pageSize,search);
				
				int resultCount = result.getList().size();
				for (int i = 0; i < resultCount; i++) {
					Map<String, Object> item = result.getList().get(i);
					
					item = BaseController.AddChangeRow(SpringContextHolder.getBean(FormColumnService.class), result.getList(), item, result.getTotal(), pageIndex, i, result.getPages(), pageSize, resultCount,"FormColumnId","OrderNumber", search);
				}
				
				RenderPage.JsonByObject(response, result);
			}
			
		}catch(Exception e){
			ErrorLog.OnWrite(e);
		}
		
	}
	@RequestMapping(params = "method=save", method = RequestMethod.POST)
	public void save(HttpServletRequest request, HttpServletResponse response) {

		try {
			String action = request.getParameter("action");
			
			String formColumnId = request.getParameter("txtFormColumnId");
			String formColumnTitle = request.getParameter("txtFormColumnTitle");
			String formId = request.getParameter("hidFormId");
			String inheritParent = request.getParameter("rdoInheritParent");
			String orderNumber = request.getParameter("txtOrderNumber");


			Map<String, Object> model = new HashMap<String, Object>();
			model.put("formColumnId", formColumnId);
			model.put("formColumnTitle", formColumnTitle);
			model.put("formId", formId);
			model.put("inheritParent", inheritParent);
			model.put("orderNumber", orderNumber);

			if (action.equals("insert")) {
				formColumnService.insert(model);
			} else if (action.equals("update")) {
				formColumnService.update(model);
			}
			
			//FormRead
			String readFieldId = request.getParameter("hidReadFieldId");
			String readFieldName = request.getParameter("txtReadFieldName");
			String readTableId = request.getParameter("hidReadTableId");
			String readTableName = request.getParameter("hidReadTableName");
			saveFormRead(readTableId,readTableName,readFieldId,readFieldName,formId,formColumnId);

			
			//FormParams
			String formParamIds=request.getParameter("hidFormParamIds");
			List<Map<String,Object>> listFormParams=new ArrayList<Map<String, Object>>();
			String[] formParamIdArray=formParamIds.split(",");
			for(int i=0;i<formParamIdArray.length;i++)
			{
				Map<String,Object> itemFormParams=new HashMap<String, Object>();
				String paramsId=formParamIdArray[i];
			
				itemFormParams.put("ParamsValueId", request.getParameter("cv_"+paramsId));
				itemFormParams.put("ParamsId", paramsId);
				itemFormParams.put("ObjectId", formColumnId);
				itemFormParams.put("ParamsValue", request.getParameter("c_"+paramsId));
				listFormParams.add(itemFormParams);
			}
			saveParams(listFormParams,formColumnId,31);

			
			//保存FormData
			FormBean formBean=formService.getBeanByKeyId(formId);
			String formData=formBean.getFormData();
			if(formData.length()>0)
			{
				Map<String,Object> formDataMap=JSON.parseObject(formData, new TypeReference<Map<String,Object>>(){});
				
				
				List<Map<String,Object>> listFormColumn=formColumnService.selectByFormId(formId);
				List<Map<String,Object>> listFormColumnParams=formColumnService.selectParamsByFormId(formId);
				List<Map<String,Object>> listFormRead=formReadService.selectByFormId(formId);
				
				formDataMap.put("FormColumn", listFormColumn);
				formDataMap.put("FormColumnParams", listFormColumnParams);
				formDataMap.put("FormRead", listFormRead);
				
				
				//保存
				formData=JSON.toJSONString(formDataMap);
				model = new HashMap<String, Object>();
				model.put("formId", formId);
				model.put("formData", formData);
				model.put("isSync", 0);
				formService.update(model);
			}
			else
			{
				//请先保存Form
			}
			
			
			RenderPage.JsonByString(response, "1");
		} catch (Exception e) {
			ErrorLog.OnWrite(e);
		}

	}
	
	private void saveFormRead(String readTableId,String readTableName,String readFieldId,String readFieldName,String formId,String formColumnId)
	{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("readType",2);
		paramMap.put("formId",formId);
		paramMap.put("formColumnId",formColumnId);
		List<Map<String, Object>> list = formReadService.select(paramMap);
		
		List<Map<String, Object>> listFormRead2=new ArrayList<Map<String, Object>>();
		String[] readFieldIdArray=readFieldId.split(",");
		String[] readFieldNameArray=readFieldName.split(",");
		String[] readTableIdArray=readTableId.split(",");
		String[] readTableNameArray=readTableName.split(",");
		for(int i=0;i<readFieldIdArray.length;i++)
		{
			Map<String, Object> itemFormRead2=new HashMap<String, Object>();
			String id="";
			for(int j=0;j<list.size();j++)
			{
				if(list.get(j).get("ReadTableId").equals(readTableIdArray[i]) && list.get(j).get("ReadFieldId").equals(readFieldIdArray[i]))
				{
					id=list.get(j).get("Id").toString();
				}
			}
			itemFormRead2.put("Id", id);
			itemFormRead2.put("ReadType", 2);
			itemFormRead2.put("FormId", formId);
			itemFormRead2.put("FormColumnId", formColumnId);
			itemFormRead2.put("ReadTableId", readTableIdArray[i]);
			itemFormRead2.put("ReadTableName", readTableNameArray[i]);
			itemFormRead2.put("ReadFieldId", readFieldIdArray[i]);
			itemFormRead2.put("ReadFieldName", readFieldNameArray[i].split("\\.")[1]);
			
			//完善，以下是后期开发功能
			itemFormRead2.put("KeyFieldName", "");
			itemFormRead2.put("SQLShowField", "");
			itemFormRead2.put("SQLFromTable", "");
			itemFormRead2.put("SQLWhereField", "");
			itemFormRead2.put("SQLOrderField", "");
			itemFormRead2.put("SQLGroupField", "");
			
			listFormRead2.add(itemFormRead2);
		}
		
		BaseController.OnSaveList(SpringContextHolder.getBean(FormReadService.class), listFormRead2, list, "Id","FormId","ReadType,FormColumnId,ReadTableId,ReadTableName,ReadFieldId,ReadFieldName",false);
	}
	
	private void saveParams(List<Map<String,Object>> listFormParams,String formControlId,int objectType)
	{
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("objectType",objectType);
		paramMap.put("objectId",formControlId);
		List<Map<String, Object>> list = formParamsService.select(paramMap);
		
		BaseController.OnSaveList(SpringContextHolder.getBean(FormParamsValueService.class), listFormParams, list, "ParamsValueId","ObjectId","ParamsId,ParamsValue",true);
	}
	
	@RequestMapping(params = "method=delete", method = RequestMethod.POST)
	public void del(HttpServletRequest request, HttpServletResponse response) {
		try{
			String[] array = StringProcess.getRequest(request.getParameter("selectitem"), "").split(",");
			for (String formColumnId : array) {
				if(formColumnId.length()>0){
					formColumnService.delete(formColumnId);
				}
			}
	
			RenderPage.JsonByString(response, "1");
		}catch(Exception e){
			ErrorLog.OnWrite(e);
		}
		
	}
}
